package com.hnkywl.sts.action.organ;

import com.google.gson.Gson;
import com.hnkywl.sts.action.flow.assign.RegectTaskSingleBackWayCmd;
import com.hnkywl.sts.entity.organ.Gsjg;
import com.hnkywl.sts.entity.organ.Lj;
import com.hnkywl.sts.entity.organ.search.QueryLj;
import com.hnkywl.sts.entity.sys.Gncz;
import com.hnkywl.sts.entity.sys.Yg;
import com.hnkywl.sts.service.flow.FlowService;
import com.hnkywl.sts.service.organ.LjwhService;
import com.hnkywl.sts.service.sys.GnczService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.util.BaseUtils;
import com.hnkywl.sts.util.EasyuiAdapter;
import com.hnkywl.sts.util.Pager;
import net.ruixin.orm.hibernate.Page;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.jbpm.api.*;
import org.jbpm.api.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: lenovo
 * Date: 13-3-22
 * Time: 上午11:12
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/organ/ljwh")
public class LjwhAction extends SimpleActionSupport {
    //页面当前位置
    private int page;
    //每页行数
    private int rows;
    //行索引
    private int index;

    private Yg yg;

    private Lj lj;

    private Long ljId;

    private String syIds;

    private String xyIds;

    private String syJcs;

    private String xyJcs;

    private QueryLj queryLj;

    private String result;

    private String taskId;

    private String content;

    private String processInstanceId;

    private String executionId;

    private FlowService flowService;

    private ProcessEngine processEngine;

    private TaskService taskService;

    private ExecutionService executionService;

    private HistoryService historyService;

    private YgService ygService;

    //功能操作
    private List<Gncz> gnczList;
    private GnczService gnczService;

    @Action("ljwh")
    public String ljwh() {
        yg = this.ygService.findYgDetail(YgService.getCurrentYg().getId());
        gnczList = gnczService.findGnczByJsAndUrl(request.getServletPath());
        return SUCCESS;
    }

    //路径
    @Action("ljwhList")
    public void ljwhList() {
        String[] propertyNames = {"id", "mc", "jyjg.id", "jyjg.qc", "jyjg.jc", "ll", "hkq", "jsfs.z", "kxg", "sfdj", "sfkjxy", "zt", "processInstanceId"};
        Page<Lj> ljs = ljwhService.findByQuery(Pager.initPager(page, rows), queryLj);
        this.renderJson(EasyuiAdapter.getJsonForDataGrid(ljs, propertyNames));
    }

    //路径明细
    @Actions({@Action("ljwh_detail"), @Action("ljwh_xs")})
    public String ljwhDetail() {
        lj = this.ljwhService.find(ljId);
        return SUCCESS;
    }

    /**
     * 根据条件获取上下游列表
     */
    @Action("sxy_list")
    public void sxyList() {
        this.renderJson(this.ljwhService.findSxy(queryLj.getLx(), queryLj.getJyjg(), queryLj.getSxy()));
    }

    @Action("lj_save")
    public void save() {
        try {
            this.ljwhService.save(lj);
            renderText("{\"statusCode\":\"200\",\"message\":\"保存成功!\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    @Action("ljwh_content")
    public String ljcontent() {
        try {
            if (lj.getId() != null) {
                lj = this.ljwhService.find(lj.getId());
                syIds = contactId(lj.getSy());
                syJcs = contactJc(lj.getSy());
                xyIds = contactId(lj.getXy());
                xyJcs = contactJc(lj.getXy());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return SUCCESS;
    }

    @Action("ljinfo")
    public void ljinfo() {
        Map<String, Object> otherParam = new HashMap<String, Object>();
        otherParam.put("list_sy", "jc");
        otherParam.put("list_xy", "jc");
        //  queryLj.setJybm(YgService.getCurrentYg().getZgjg().getId().toString());
        String ljinfoJson = BaseUtils.fetchCollectionToJson(this.ljwhService.findAll(), otherParam, "id", "mc", "jyjg.id", "jyjg.qc", "jyjg.jc", "ll", "hkq", "jypz", "dbfs", "jsfs.id", "kxg", "lx", "sy", "xy");
        this.renderJson("[" + ljinfoJson + "]");
    }

    @Action("ljinfosxy")
    public void ljinfosxy() {
        lj = this.ljwhService.find(ljId);
        Map<String, Object> otherParam = new HashMap<String, Object>();
        otherParam.put("lx", "sy");
        String ljjson = BaseUtils.fetchCollectionToJson(lj.getSy(), otherParam, "id", "jc", "qc");
        if (StringUtils.isNotEmpty(ljjson) && lj.getXy() != null && lj.getXy().size() > 0)
            ljjson += ",";
        otherParam.put("lx", "xy");
        ljjson += BaseUtils.fetchCollectionToJson(lj.getXy(), otherParam, "id", "jc", "qc");
        this.renderJson("[" + ljjson + "]");
    }

    @Action("bgljInfo")
    public void bgljinfo() {
        Map<String, Object> data = ljwhService.bgljInfo(ljId);
        Gson gson = new Gson();
        renderJson(gson.toJson(data));
    }

    private String contactId(List<Gsjg> sylist) {
        String result = "";
        for (Gsjg sy : sylist) {
            result += sy.getId() + ",";
        }
        return StringUtils.isNotEmpty(result) ? result.substring(0, result.length() - 1) : "";
    }

    private String contactJc(List<Gsjg> sylist) {
        String result = "";
        for (Gsjg sy : sylist) {
            result += sy.getJc() + ",";
        }
        return StringUtils.isNotEmpty(result) ? result.substring(0, result.length() - 1) : "";
    }

    @Action("ljByProcessInstance")
    public void ljByProcessInstance() {
        Lj lj;
        String processInstanceId = StringUtils.EMPTY;
        Execution execution = this.executionService.findExecutionById(executionId);
        if (execution != null) {
            lj = this.ljwhService.findLjDetailByProcessInstance(execution.getProcessInstance().getId());
            processInstanceId = execution.getProcessInstance().getId();
        } else {
            lj = this.ljwhService.findLjDetailByProcessInstance(executionId);
            processInstanceId = executionId;
        }
        String ljJson = "{'id':'" + lj.getId() + "','type':'LJ','businessNo':'" + lj.getMc() + "','processInstanceId':'" + processInstanceId + "'}";
        this.renderText(ljJson);
    }

    @Action("lj_delete")
    public void delete() {
        try {
            this.ljwhService.delete(ljId);
            renderText("{\"statusCode\":\"200\",\"message\":\"删除成功!\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    @Action("lj_commit")
    public void commitLj() {
        try {
            lj = this.ljwhService.find(ljId);
            if (this.flowService.checkFlowStart("路径流程")) {
                String contain = StringUtils.EMPTY;
                if (lj.getCreateDepartment().getId() == 30 || lj.getCreateDepartment().getId() == 26
                        || lj.getCreateDepartment().getId() == 27 || lj.getCreateDepartment().getId() == 28
                        || lj.getCreateDepartment().getId() == 29 || lj.getCreateDepartment().getId() == 8131
                        || lj.getCreateDepartment().getId() == 8132
                        || lj.getCreateDepartment().getId() == 8133
                        || lj.getCreateDepartment().getId() == 8134)
                    contain = "贸易部";
                String processInstanceId = this.flowService.regTask(lj.getProcessInstanceId(), "路径流程", contain);
                lj.setProcessInstanceId(processInstanceId);
                lj.setZt("ytj");
            } else
                lj.setZt("ysp");
            this.ljwhService.changeState(lj);
            renderText("{\"statusCode\":\"200\", \"message\":\"提交路径成功\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    //解冻路径
    @Action("start_lj")
    public void startLj() {
        try {
            this.ljwhService.startLj(ljId);
            renderJson("{\"statusCode\":\"200\", \"message\":\"路径解冻成功！\", \"operationType\":\"update\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderJson("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    //冻结路径
    @Action("stop_lj")
    public void stopLj() {
        try {
            this.ljwhService.stopLj(ljId);
            renderJson("{\"statusCode\":\"200\", \"message\":\"路径冻结成功！\", \"operationType\":\"update\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderJson("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    //路径可修改
    @Action("start_lj_update")
    public void startLjUpdate() {
        try {
            this.ljwhService.startLjUpdate(ljId);
            renderJson("{\"statusCode\":\"200\", \"message\":\"路径可修改！\", \"operationType\":\"update\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderJson("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    //路径不可修改
    @Action("stop_lj_update")
    public void stopLjUpdate() {
        try {
            this.ljwhService.stopLjUpdate(ljId);
            renderJson("{\"statusCode\":\"200\", \"message\":\"路径不可修改！\", \"operationType\":\"update\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderJson("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    @Action(value = "examineTask")
    public void examineTask() throws Exception {
        if (this.result.equals("审核")) {
            Map<String, Object> var = new HashMap<String, Object>();
            var.put("owner", YgService.getCurrentYg().getId());
            var.put("opera", YgService.getCurrentYgGs() + "--" + YgService.getCurrentYgName());
            var.put("result", "审核通过");
            var.put("content", content);
            var.put("time", new Date());
            Task currentTask = this.taskService.getTask(taskId);
            String executionId = currentTask.getExecutionId();
            executionService.createVariables(executionId, var, true);
            var.put("status", result);

            Execution execution = this.executionService.findExecutionById(executionId);
            Lj lj = ljwhService.findLjDetailByProcessInstance(execution.getProcessInstance().getId());

            if (lj.getCreateDepartment().getId() == 30 || lj.getCreateDepartment().getId() == 26
                    || lj.getCreateDepartment().getId() == 27 || lj.getCreateDepartment().getId() == 28
                    || lj.getCreateDepartment().getId() == 29 || lj.getCreateDepartment().getId() == 8131
                    || lj.getCreateDepartment().getId() == 8132
                    || lj.getCreateDepartment().getId() == 8133
                    || lj.getCreateDepartment().getId() == 8134)
                var.put("contain", "贸易部");
            else
                var.put("contain", StringUtils.EMPTY);
            this.taskService.completeTask(taskId, var);

//            Execution execution = this.executionService.findExecutionById(executionId);
//            if (execution != null) {
//                Lj lj = ljwhService.findLjDetailByProcessInstance(execution.getProcessInstance().getId());
            if (lj.getZt().equals("ybc")) {
                lj.setZt("ytj");
                ljwhService.save(lj);
            }
//            }
        } else {
            String result = processEngine.execute(new RegectTaskSingleBackWayCmd(taskId, content));
            if (result.equals("change")) {
                //修改状态  ytj--->ybc
                String executionId = this.historyService.createHistoryTaskQuery().taskId(taskId).uniqueResult().getExecutionId();
                Execution execution = this.executionService.findExecutionById(executionId);
                Lj lj = ljwhService.findLjDetailByProcessInstance(execution.getProcessInstance().getId());
                lj.setZt("ybc");
                ljwhService.save(lj);
            }
        }
        this.renderText("{\"statusCode\":\"200\", \"message\":\"审核流程成功\"}");
    }

    private LjwhService ljwhService;

    public List<Gncz> getGnczList() {
        return gnczList;
    }

    public void setGnczList(List<Gncz> gnczList) {
        this.gnczList = gnczList;
    }

    @Autowired
    public void setGnczService(GnczService gnczService) {
        this.gnczService = gnczService;
    }

    @Autowired
    public void setLjwhService(LjwhService ljwhService) {
        this.ljwhService = ljwhService;
    }

    @Autowired
    public void setFlowService(FlowService flowService) {
        this.flowService = flowService;
    }

    @Autowired
    public void setExecutionService(@Qualifier("executionService") ExecutionService executionService) {
        this.executionService = executionService;
    }

    @Autowired
    public void setTaskService(@Qualifier("taskService") TaskService taskService) {
        this.taskService = taskService;
    }

    @Autowired
    public void setProcessEngine(@Qualifier("processEngine") ProcessEngine processEngine) {
        this.processEngine = processEngine;
    }

    @Autowired
    public void setHistoryService(@Qualifier("historyService") HistoryService historyService) {
        this.historyService = historyService;
    }

    @Autowired
    public void setYgService(YgService ygService) {
        this.ygService = ygService;
    }

    public Yg getYg() {
        return yg;
    }

    public void setYg(Yg yg) {
        this.yg = yg;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public Lj getLj() {
        return lj;
    }

    public void setLj(Lj lj) {
        this.lj = lj;
    }

    public Long getLjId() {
        return ljId;
    }

    public void setLjId(Long ljId) {
        this.ljId = ljId;
    }

    public String getSyIds() {
        return syIds;
    }

    public void setSyIds(String syIds) {
        this.syIds = syIds;
    }

    public String getXyIds() {
        return xyIds;
    }

    public void setXyIds(String xyIds) {
        this.xyIds = xyIds;
    }

    public QueryLj getQueryLj() {
        return queryLj;
    }

    public void setQueryLj(QueryLj queryLj) {
        this.queryLj = queryLj;
    }

    public String getProcessInstanceId() {
        return processInstanceId;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    public String getContent() {
        return content;
    }

    public String getSyJcs() {
        return syJcs;
    }

    public void setSyJcs(String syJcs) {
        this.syJcs = syJcs;
    }

    public String getXyJcs() {
        return xyJcs;
    }

    public void setXyJcs(String xyJcs) {
        this.xyJcs = xyJcs;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getExecutionId() {
        return executionId;
    }

    public void setExecutionId(String executionId) {
        this.executionId = executionId;
    }

    public void setProcessInstanceId(String processInstanceId) {
        this.processInstanceId = processInstanceId;
    }
}
